import Taro from '@tarojs/taro';

export const networkVerify = params => params;

/** 锁定屏幕方向-竖屏 */
export const screenOrientationLockAsyncVertical = () => {};
/** 锁定屏幕方向-横屏 */
export const screenOrientationLockAsyncHorizontal = () => {};

/**
 * 预览文件
 * previewFile('https://501351981.github.io/vue-office/examples/dist/static/test-files/test.docx')
 * @param url
 */
export const previewFile = (url: string) => {
  if (!url || typeof url !== 'string') return;
  let lowerFileUrl = url.toLowerCase();
  let fileType = '';
  if (lowerFileUrl.includes('.docx')) {
    fileType = 'docx';
  } else if (lowerFileUrl.includes('.pdf')) {
    fileType = 'pdf';
  } else if (lowerFileUrl.includes('.xlsx')) {
    fileType = 'excel';
  } else if (strIncludeArray(lowerFileUrl, ['.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp', '.svg', '.tiff'])) {
    fileType = 'img';
  } else if (strIncludeArray(lowerFileUrl, ['.txt', '.json'])) {
    fileType = 'txt';
  }
  function strIncludeArray(str, array) {
    for (let i = 0; i < array.length; i++) {
      if (str.includes(array[i])) {
        return true;
      }
    }
    return false;
  }
  if (fileType === 'img') {
    Taro.previewImage({
      urls: [url],
      current: 0,
    });
  } else {
    if (process.env.TARO_ENV === 'h5') {
      // @ts-ignore
      window.open(url);
      return;
    }
    Taro.downloadFile({
      url: url,
      success: function (res) {
        console.log('download success', res);
        const filePath = res.tempFilePath;
        Taro.openDocument({
          filePath: filePath,
          success: function () {
            console.log('打开文档成功');
          },
        });
      },
      fail: function (res) {
        console.warn(res);
        Taro.showToast({ title: '下载失败', icon: 'none' });
      },
      complete: function (res) {},
    }).catch(err => {
      console.warn(err);
    });
  }
};
